package com.myservice;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
 * web服务器主程序：
 * 1.解析客户端请求协议
 * 2.根据协议内容向用户返回资源
 * */
public class Processer extends Thread {
	
	private Socket socket = null;//socket对象
	
	private InputStream in = null;//输入流对象.
	
	private PrintStream out = null;//输出流对象
	
	private final static String WEB_ROOT = "F:\\payment\\work2\\webservice\\";//资源目录
	/**
	 * 构造器初始化输入、输出流以及socket
	 * */
	public Processer(Socket socket) {
		this.socket = socket;
		try {
			in = this.socket.getInputStream();//得到输入流
			out = new PrintStream(this.socket.getOutputStream());//得到输出流
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 启动线程
	 * */
	public void run(){
		//解析输入
		String filename = parse(in);
		//服务器返回请求资源
		sendFile(filename);
	}
	/**
	 * 解析输入流
	 * */
	public String parse (InputStream in){
		String filename ="";
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			//获取协议的第一行  ："协议的状态号 协议内容 协议的版本"
			String  httpMessage =  br.readLine();
			System.out.println("httpMessage="+httpMessage);
			String [] content = httpMessage.split(" ");//解析协议
			if(content.length!=3){
				sendErrorMessage(400, "get 400 Error！");
				return null;
			}
			filename = content[1];//请求协议的内容
		} catch (IOException e) {
			e.printStackTrace();
		}
		return filename;
	}
	/**
	 * 向客户端发送消息
	 * */
	public void sendErrorMessage(int errorCode,String errorMessage){
		out.println("HTTP/1.2"+errorCode+" "+errorMessage);
		out.println("content-type; text/html");
		out.println();
		out.println("<html>");
		out.println("<body>");
		out.println("<title>error Message");
		out.println("</title>");
		out.println("<h1>");
		out.println("errorCode:"+errorCode+",Message:"+errorMessage);
		out.println("</h1>");
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
	}
	/**
	 * 返回用户请求的资源
	 * */
	public void sendFile(String fileName){
		File file = new File(this.WEB_ROOT+fileName);//客户请求的文件
		if(!file.exists()){//判断资源文件是否存在
			sendErrorMessage(404, "get 404 Error!");
			return;
		}
		try {
			InputStream in = new FileInputStream(file);
			byte [] content = new byte[(int)file.length()];
			in.read(content);//将文件内容读取到输出流中
			out.println("HTTP/1.1 200 queryfile");
			out.println("content-length:"+content.length);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
